# -*- coding: utf-8 -*-

from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool
import os

LDAP_SERVER_POOL = ["10.39.95.5", "10.39.95.6"]
LDAP_SERVER_PORT = 389
ADMIN_DN = "administrator"
ADMIN_PASSWORD = "Qdingnet@2018"
SEARCH_BASES = ["ou=产研领域,ou=千丁互联,dc=qdingnet,dc=cn"]


def ldap_auth():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ServiceConn.settings")
    import django
    django.setup()
    from rbac import models
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool, user=ADMIN_DN, password=ADMIN_PASSWORD, check_names=True, lazy=False,
                      raise_exceptions=False)
    conn.open()
    conn.bind()

    ldap_users = set()

    for SEARCH_BASE in SEARCH_BASES:
        print(SEARCH_BASE)
        res = conn.search(
            search_base=SEARCH_BASE,
            # search_filter = '(sAMAccountName={})'.format(username),
            search_filter='(sAMAccountName=*)',
            # search_filter = '(department=运维中心)',
            # search_filter = '(ou=技术研发部)',
            search_scope=SUBTREE,
            attributes=['department', 'mail', 'sAMAccountName', 'telephoneNumber', 'displayName', 'title'],
            # paged_size = 100
        )
        print(res)

        if res:
            entry = conn.response
            print(entry)
            for i in entry:
                attr_dict = i['attributes']
                print(attr_dict)
                depart_obj = models.Department.objects.filter(name=attr_dict["department"])
                if depart_obj:
                    attr_dict["department_id"] = depart_obj[0].id
                else:
                    depart_obj = models.Department.objects.create(name=attr_dict["department"])
                    attr_dict["department_id"] = depart_obj.id
                ldap_dict = dict(attr_dict)
                if ldap_dict["department"] == "运维中心":
                    roles = models.Role.objects.all()
                else:
                    roles = models.Role.objects.filter(title="dev").all()
                ldap_dict.pop('department')
                aa = ldap_dict
                ldap_users.add(aa["sAMAccountName"])
                # print("crnt,cront,cront!!!!")
                ee = models.User.objects.filter(sAMAccountName=aa["sAMAccountName"])
                if ee:
                    print("eee",ee)
                    ee.update(**aa)
                    ee[0].roles.add(*roles)
                else:
                    ff = models.User.objects.create(**aa)
                    ff.roles.add(*roles)

    mo_users = set([uu.sAMAccountName for uu in models.User.objects.all()])
    del_users = mo_users - ldap_users
    for dd in del_users:
        models.User.objects.filter(sAMAccountName=dd)

# ldap_auth()
